import SimpleHTTPServer
import BaseHTTPServer
from time import sleep
import logging
import threading
import httplib

class StoppableHttpRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """http request handler with QUIT stopping the server"""
    
    def do_QUIT(self):
        """send 200 OK response, and set server.stop to True"""
        self.send_response(200)
        self.end_headers()
        self.server.stop = True
        
    def do_GET(self):
        self.logger = logging.getLogger("HTTP")
        self.logger.debug("path = %s" % self.path)
        if self.path == "/testdata/error.txt":
            f = self.send_head()
            if f:
                sleep(6)
                self.copyfile(f, self.wfile)
                f.close()
        else:
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

class StoppableHttpServer(BaseHTTPServer.HTTPServer):
    """http server that reacts to self.stop flag"""

    def serve_forever(self):
        """Handle one request at a time until stopped."""
        self.stop = False
        while not self.stop:
            self.handle_request()

class Runner():
    server = StoppableHttpServer(("", 8888), StoppableHttpRequestHandler)
    
    def start(self):
        thread = threading.Thread(target=self.server.serve_forever)
        thread.start()

    def stop(self):
        """send QUIT request to http server running on localhost:<8888>"""
        conn = httplib.HTTPConnection("localhost:%d" % 8888)
        conn.request("QUIT", "/")
        conn.getresponse()

